package wineshop.service.customer;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.*;

import wineshop.domain.market.Customer;

@Stateless
@LocalBean
public class CustomerBean {
	@PersistenceContext
	private EntityManager em;

	public Customer getCustomerByUserName(String username) {
		TypedQuery<Customer> query = em.createQuery("select c from " + Customer.class.getSimpleName()
				+ " c where c.username=:username", Customer.class);
		query.setParameter("username", username);
		Customer customer;
		try{
			customer = query.getSingleResult();
		}catch (NoResultException nre){
			customer = null;
		}
		return customer;
	}

	public void createCustomer(Customer customer, char[] password) {
		customer.setPassword(password);
		em.persist(customer);
	}

	public boolean isValidCustomer(String username, char[] password) {
		Customer customer = getCustomerByUserName(username);
		return customer.hasPassword(password);
	}
}
